<template>
  <div>
    <el-form :inline="true"
             :model="searchParams"
             class="filter-form"
             @submit.prevent>
      <el-form-item label="文章名称">
        <el-input v-model="searchParams.title" placeholder="请输入文章名称" />
      </el-form-item>
      <el-form-item label="提交时间">
        <el-date-picker
          v-model="searchParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          :disabled="!multipleSelection.length"
          @click="handleBatchApprove"
        >批量通过</el-button
        >
        <el-button
          type="danger"
          :disabled="!multipleSelection.length"
          @click="handleBatchReject"
        >批量驳回</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="list"
      border
      style="width: 100%; margin-top: 16px"
      @selection-change="handleSelectionChange"
      :loading="loading || searchLoading"
      @row-click="viewDetail"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="文章名称" min-width="200" />
      <el-table-column prop="submitTime" label="提交时间" min-width="180" />
      <el-table-column prop="status" label="状态" min-width="180" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <template v-if="scope.row.status === 'review'">
            <el-button type="success"
                       size="small"
                       @click.stop="handleApprove(scope.row)"
            >通过</el-button
            >
            <el-button type="danger"
                       size="small"
                       @click.stop="handleReject(scope.row)"
            >驳回</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right; margin-top: 16px">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="params.size"
        :current-page="params.page"
        @current-change="setPage"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useList } from '@/composables/useList';
import { useRequest } from '@/composables/useRequest';
import { getPendingArticles, reviewArticle } from '@/api/piece';

const router = useRouter();

interface Article {
  id: number;
  title: string;
  submitTime: string;
  status: string;
}

const searchParams = ref({
  title: '',
  dateRange: [],
  page: 1,
  size: 20
});

const { list, total, loading, params, query, setPage } = useList<Article>(
  getPendingArticles,
  searchParams.value
);
const { loading: searchLoading, run: runSearch } = useRequest();

const multipleSelection = ref<Article[]>([]);

async function handleSearch() {
  searchParams.value.page = 1;
  await runSearch(() => query({ ...searchParams.value }));
}

async function handleReset() {
  searchParams.value = {
    title: '',
    dateRange: [],
    page: 1,
    size: 20
  };
  await runSearch(() => query({ ...searchParams.value }));
}

function handleSelectionChange(val: Article[]) {
  multipleSelection.value = val;
}

async function handleApprove(row: Article) {
  try {
    await ElMessageBox.confirm('确定要通过该文章审核吗？', '审核确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await reviewArticle(row.id, { deal: 1 });
    query({ ...searchParams.value });
    ElMessage.success('审核通过');
  } catch (err) {
    if (err !== 'cancel') {
      console.error('审核通过失败:', err);
    }
  }
}

async function handleReject(row: Article) {
  try {
    await ElMessageBox.confirm('确定要驳回该文章吗？', '驳回确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await reviewArticle(row.id, { deal: 2 });
    query({ ...searchParams.value });
    ElMessage.success('审核驳回');
  } catch (err) {
    if (err !== 'cancel') {
      console.error('审核驳回失败:', err);
    }
  }
}

async function handleBatchApprove() {
  // 只允许 status 为 review 的文章参与批量审核
  const reviewList = multipleSelection.value.filter((item) => item.status === 'review');
  if (reviewList.length === 0) {
    ElMessage.warning('请选择待审核(review)的文章！');
    return;
  }
  try {
    await ElMessageBox.confirm(
      `确定要批量通过选中的 ${reviewList.length} 篇待审核文章吗？`,
      '批量审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await Promise.all(reviewList.map((item) => reviewArticle(item.id, { deal: 1 })));
    ElMessage.success('批量审核通过');
    query({ ...searchParams.value });
  } catch (err) {
    if (err !== 'cancel') {
      console.error('批量审核通过失败:', err);
    }
  }
}

async function handleBatchReject() {
  // 只允许 status 为 review 的文章参与批量驳回
  const reviewList = multipleSelection.value.filter((item) => item.status === 'review');
  if (reviewList.length === 0) {
    ElMessage.warning('请选择待审核(review)的文章！');
    return;
  }
  try {
    await ElMessageBox.confirm(
      `确定要批量驳回选中的 ${reviewList.length} 篇待审核文章吗？`,
      '批量驳回确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    await Promise.all(reviewList.map((item) => reviewArticle(item.id, { deal: 2 })));
    ElMessage.success('批量审核驳回');
    query({ ...searchParams.value });
  } catch (err) {
    if (err !== 'cancel') {
      console.error('批量审核驳回失败:', err);
    }
  }
}

function viewDetail(row: Article) {
  router.push({ name: 'ArticleDetail', params: { id: row.id } });
}

onMounted(() => {
  query({ ...searchParams.value });
});
</script>

<style scoped>
.filter-form {
  margin-bottom: 16px;
}
</style>
